<template>
  <div>
    <div style="height:6vh;background-color:#fff;padding: 10px 20px;">
      <span style="line-height: 60px;font-size: 20px;">培训人员</span>
      <el-button
          v-if="getUser.level >= 20"
          type="primary"
          style="float: right; margin-top: 13px;"
          @click="beforeAddTrainingEmp">
        新增培训人员
      </el-button>
    </div>

    <!-- 参与人弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :before-close="handleClose">
      <el-form label-width="120px" :model="trainingEmpForm" :rules="rules" ref="trainingEmpForm">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="trainingId">
              <el-select
                  v-model="trainingEmpForm.trainingId"
                  placeholder="选择培训项目"
                  clearable
                  style="width:100%">
                <el-option
                    v-for="tos in trainingOptions"
                    :key="tos.id"
                    :label="tos.title"
                    :value="tos.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工" prop="employeeId">
              <el-select
                  v-model="trainingEmpForm.employeeId"
                  placeholder="请选择员工"
                  filterable
                  style="width:100%">
                <el-option
                    v-for="emp in employeeOptions"
                    :key="emp.id"
                    :label="emp.name"
                    :value="emp.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出勤状态" prop="status">
              <el-select
                  v-model="trainingEmpForm.status"
                  placeholder="选择状态"
                  clearable
                  style="width:100%">
                <el-option label="参与" :value="1"></el-option>
                <el-option label="缺席" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考核分数" prop="score">
              <el-input-number
                  v-model="trainingEmpForm.score"
                  :min="0"
                  :max="100"
                  :precision="1"
                  style="width:100%"
                  placeholder="请输入分数">
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitTrainingEmp">保存</el-button>
      </template>
    </el-dialog>

    <!-- 参与员工查询 -->
    <el-card style="margin: 20px; height: 70px;">
      <el-form :inline="true" @submit.native.prevent>
        <el-form-item label="项目名称">
          <el-select
              v-model="searchForm.trainingId"
              placeholder="选择培训项目"
              clearable
              style="width:100%">
            <el-option
                v-for="tos in trainingOptions"
                :key="tos.id"
                :label="tos.title"
                :value="tos.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参与状态">
          <el-select
              v-model="searchForm.status"
              placeholder="选择状态"
              clearable
              style="width:100%">
            <el-option label="参与" :value="1"></el-option>
            <el-option label="缺席" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetParticipantSearch">重置</el-button>
          <el-button type="primary" @click="loadParticipantList">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 参与员工列表 -->
    <el-card style="margin: 20px;">
      <el-table :data="participantList">
        <el-table-column label="序号" type="index" align="center" width="60"></el-table-column>
        <el-table-column label="培训项目" prop="title" align="center"></el-table-column>
        <el-table-column label="员工姓名" prop="employeeId" align="center">
          <template #default="{row}">
            {{ formatEmployeeName(row.employeeId) }}
          </template>
        </el-table-column>
        <el-table-column label="参与状态" align="center">
          <template #default="{row}">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '参与' : '缺席' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="考核分数" prop="score" align="center">
          <template #default="{row}">
            {{ row.score || '未评分' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right">
          <template #default="{row}">
            <el-button link type="text" :disabled="getUser.level < 20" @click="editParticipant(row)">编辑</el-button>
            <el-button link type="text" :disabled="getUser.level < 20" @click="deleteParticipant(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          style="margin-top: 20px;"
          @size-change="handleParticipantSizeChange"
          @current-change="handleParticipantCurrentChange"
          :current-page="participantPagination.current"
          :page-sizes="[3, 4, 5]"
          :page-size="participantPagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="participantPagination.total">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';
import { Message } from 'element-ui';
import qs from "qs";

export default {
  data() {
    // 分数验证规则
    const validateScore = (rule, value, callback) => {
      if (value === null || value === undefined) {
        return callback();
      }
      if (value < 0 || value > 100) {
        callback(new Error('分数范围0-100'));
      } else {
        callback();
      }
    };

    return {
      getUser: this.$getUser(),
      dialogVisible: false,
      dialogTitle: '新增培训人员',
      trainingOptions: [],
      employeeOptions: [],
      trainingEmpForm: {
        id: null,
        trainingId: null,
        employeeId: null,
        status: 1,
        score: null
      },
      rules: {
        trainingId: [
          { required: true, message: '请选择培训项目', trigger: 'blur' }
        ],
        employeeId: [
          { required: true, message: '请选择员工', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择参与状态', trigger: 'blur' }
        ],
        score: [
          { validator: validateScore, trigger: 'blur' }
        ]
      },
      searchForm: {
        trainingId: null,
        status: null
      },
      participantList: [],
      participantPagination: {
        current: 1,
        size: 3,
        total: 0
      }
    };
  },
  mounted() {
    this.loadTrainingOptions();
    this.loadEmployeeOptions();
    this.loadParticipantList();
  },
  methods: {
    // 加载培训选项
    loadTrainingOptions() {
        axios.get(this.$BASE_URL+'/v1/training/list')
            .then(res => {
              if (res.data.state === 2000) {
                this.trainingOptions = res.data.data.trainingList;
              }
            })
    },

    // 加载员工选项
    loadEmployeeOptions() {
        axios.get(this.$BASE_URL+'/v1/user/list')
            .then(res => {
              if (res.data.state === 2000) {
                this.employeeOptions = res.data.data.userList;
              }
            })
    },

    // 加载参与列表
    loadParticipantList() {
        const data = qs.stringify({
          pageCurrent: this.participantPagination.current,
          pageSize: this.participantPagination.size,
          ...this.searchForm
        });
        axios.get(this.$BASE_URL+'/v1/training/employee/list?'+data)
            .then(res => {
              if (res.data.state === 2000) {
                this.participantList = res.data.data.trainingEmployeeList;
                this.participantPagination.total = res.data.data.total;
              }else {
                Message.error(res.data.message || '操作失败');
              }
            })
    },

    // 新增参与记录
    beforeAddTrainingEmp() {
      this.dialogTitle = '新增培训人员';
      this.trainingEmpForm = {
        id: null,
        trainingId: null,
        employeeId: null,
        status: 1,
        score: null
      };
      this.dialogVisible = true;
    },

    // 编辑参与记录
    editParticipant(row) {
      this.dialogTitle = '编辑参与记录';
      this.trainingEmpForm = {
        id: row.id,
        trainingId: row.trainingId,
        employeeId: row.employeeId,
        status: row.status,
        score: row.score
      };
      this.dialogVisible = true;
    },

    // 提交参与记录
    submitTrainingEmp() {
      this.$refs.trainingEmpForm.validate(async valid => {
        if (valid) {
            axios.post(this.$BASE_URL + '/v1/training/employee/save', qs.stringify(this.trainingEmpForm))
                .then(res => {
                  if (res.data.state === 2000) {
                    Message.success('保存成功');
                    this.dialogVisible = false;
                    this.loadParticipantList();
                  }else {
                    Message.error(res.data.message || '保存失败');
                  }
                });
        }
      });
    },

    // 删除参与记录
    deleteParticipant(id) {
        this.$confirm('确定要删除该参与记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          axios.post(this.$BASE_URL + `/v1/training/employee/delete/${id}`)
              .then(res => {
                if (res.data.state === 2000) {
                  Message.success('删除成功');
                  this.loadParticipantList();
                }else {
                  Message.error(res.data.message || '删除失败');
                }
              });
        })
        .catch(() => {
          Message.info('已取消删除');
        });


    },

    // 格式化员工姓名
    formatEmployeeName(employeeId) {
      const employee = this.employeeOptions.find(e => e.id === employeeId);
      return employee?.name || '未知员工';
    },

    // 重置查询条件
    resetParticipantSearch() {
      this.searchForm = {
        trainingId: null,
        status: null
      };
      this.participantPagination.current = 1;
      this.loadParticipantList();
    },

    // 分页处理
    handleParticipantSizeChange(size) {
      this.participantPagination.size = size;
      this.participantPagination.current = 1;
      this.loadParticipantList();
    },

    handleParticipantCurrentChange(current) {
      this.participantPagination.current = current;
      this.loadParticipantList();
    },

    // 关闭对话框
    handleClose() {
      this.dialogVisible = false;
      this.$refs.trainingEmpForm.resetFields();
    }
  }
};
</script>

<style scoped>

</style>